# -*-coding:utf-8-*-

import logging
import urllib
import json


class BaseAPI(object):
    def __init__(self, *args, **kwargs):
        self.logger = logging.getLogger()
        if 'access_token' in kwargs:
            self.access_token = kwargs['access_token']
            self.query = 'access_token=%s' % self.access_token
        self.base_test_case_obj = kwargs['base_test_case_obj']

    def query_from_kwargs(self, **kwargs):
        query = urllib.urlencode(kwargs)
        if 0 == query:
            query = self.query
        else:
            query += '&%s' % self.query
        return query

    def assert_response_success(self, response):
        return self.base_test_case_obj.assert_response_success(response)

    def assert_response_success_data(self, response, **kwargs):
        assert_error_code = kwargs.pop('assert_error_code') if 'assert_error_code' in kwargs else 0
        if 0 == assert_error_code:
            return self.assert_response_success(response)['data']
        else:
            response = json.loads(response.body)
            self.assertTrue(not response['result'] and response['error_code'] == assert_error_code,
                            response['error_message'])
            return None

    def assert_response_error(self, response, assert_error_code):
        return self.base_test_case_obj.assert_response_error(response, assert_error_code)

    def assertTrue(self, *args, **kwargs):
        return self.base_test_case_obj.assertTrue(*args, **kwargs)

    def assertEqual(self, *args, **kwargs):
        return self.base_test_case_obj.assertEqual(*args, **kwargs)
